package best.driver.android.common.network;

import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class ApiArrayRequest<T> extends ApiRequest<ArrayList<T>> {
    private Class<T> mTargetClass;
    
    private String jsonkey;
    public void setJsonKey(String k){
    	jsonkey = k;
    }

    public ApiArrayRequest(Class<T> cls, Method method) {
        super(method);
        this.mTargetClass = cls;
    }
    

    @Override
    protected ArrayList<T> processJsonResponse(Object response) {
        ArrayList<T> result = new ArrayList<T>();

        if (response == null) {
            return result;
        }
        try {
			Gson gson = new Gson();
			JSONArray jsonArray = null;
			if(!TextUtils.isEmpty(jsonkey)){
				JSONObject jo = (JSONObject)response;
				jsonArray = jo.getJSONArray(jsonkey);
			}else{
				jsonArray = (JSONArray) response;
			}
			for (int idx = 0; idx < jsonArray.length(); idx++) {
			    JSONObject json = jsonArray.optJSONObject(idx);
			    result.add(gson.fromJson(json.toString(), mTargetClass));
			}
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
        return result;
    }
}
